#include <STC15F2K60S2.H>
#include "intrins.h"

sbit DQ = P1^4;

unsigned char Onewire_Init()
{
	unsigned char ackbit;
	unsigned char i, j;
	DQ = 1;
	_nop_();
	DQ = 0;
	i = 6;j = 93;//500us
	do
	{
		while (--j);
	} while (--i);
	DQ = 1;
	i = 1;j = 162;;//60us
	do
	{
		while (--j);
	} while (--i);
	ackbit = DQ;
	i = 6;j = 93;//500us
	do
	{
		while (--j);
	} while (--i);
	return ackbit;
}


void Write_bit(unsigned char Bit)
{
	unsigned char i;
	DQ = 0;
	i = 39;
	while (--i);//15us
	DQ = Bit;
	i = 122;
	while (--i);
	DQ=1;
}

unsigned char Read_bit(void)
{
	unsigned char Bit;
	unsigned char i,j;
	DQ = 0;
	_nop_();
	i = 11;
	while (--i);//5us
	DQ = 1;
	_nop_();
	i = 11;
	while (--i);//5us
	Bit = DQ;
	i = 1;j = 134;//50us
	do
	{
		while (--j);
	} while (--i);
	return Bit;
}


void Write_Byte(unsigned char Byte)
{
	unsigned char i;
	for(i=0;i<8;i++)
	{
		_nop_();
		Write_bit(Byte&(0x01<<i));
	}
}



unsigned char Read_Byte()
{
	unsigned char Byte = 0x00;
	unsigned char i;
	for(i=0;i<8;i++)
	{
		if(Read_bit()){Byte|=(0x01<<i);}
		_nop_();
	}
	return Byte;
}


